//
// Created by shenbin on 2022/4/17.
// https://leetcode-cn.com/problems/merge-two-sorted-lists/
//

#ifndef ALGORITHM_TRAINNING_W01_H02_LC21_H
#define ALGORITHM_TRAINNING_W01_H02_LC21_H

class LeetCode21 {
public:
    struct ListNode {
        int val;
        ListNode *next;

        ListNode() : val(0), next(nullptr) {}

        ListNode(int x) : val(x), next(nullptr) {}

        ListNode(int x, ListNode *next) : val(x), next(next) {}
    };

    ListNode *mergeTowLists(ListNode *list1, ListNode *list2) {
        ListNode *protect = new ListNode(-1);
        ListNode *ptr = protect;
        while (list1 != nullptr && list2 != nullptr) {
            if (list1->val < list2->val) {
                ptr->next = list1;
                list1 = list1->next;
            } else {
                ptr->next = list2;
                list2 = list2->next;
            }
            ptr = ptr->next;
        }
        if (list1 == nullptr) {
            ptr->next = list2;
        } else {
            ptr->next = list1;
        }
        return protect->next;
    }
};

#endif //ALGORITHM_TRAINNING_W01_H02_LC21_H
